package com.dycong.common.IO.netty.first;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.logging.LoggingHandler;
import org.apache.log4j.Logger;

import java.nio.ByteBuffer;

/**
 * Created by dycong on 2017/3/13.
 */
@ChannelHandler.Sharable        //@Sharable 标识这类的实例之间可以在 channel 里面共享
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    static final Logger log=Logger.getLogger(EchoServerHandler.class);
    static int count = 0;
    LoggingHandler loggingHandler = new LoggingHandler(EchoServerHandler.class);

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println(("server!" + (++count) + Thread.currentThread()));
        ctx.fireChannelRegistered();
    }

    //每个信息入站都会调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = Unpooled.copiedBuffer(msg.toString().getBytes());
        ByteBuffer buffer = ByteBuffer.allocate(in.readableBytes());
        in.readBytes(buffer);
        System.out.println("accept: " + new String(buffer.array()) + ":" + Thread.currentThread());
        //将所接收的消息返回给发送者。注意，这还没有冲刷数据
        //// TODO: 2017/4/5 flip()，由于未加flip()，调试一小时 
        buffer.flip();
        ctx.writeAndFlush(Unpooled.copiedBuffer(buffer));
    }

    //通知处理器最后的 channelRead() 是当前批处理中的最后一条消息时调用
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("sssssssssssssssssssssssssss");
        ctx.flush();
//        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)//4冲刷所有待审消息到远程节点。关闭通道后，操作完成
//                .addListener(ChannelFutureListener.CLOSE)
//                .addListener(new ChannelFutureListener() {
//                    @Override
//                    public void operationComplete(ChannelFuture future) throws Exception {
//                        if (future.isSuccess())
//                            log.info("read successful");
//                        else
//                            log.info("read failed"+future.cause());
//                    }
//                });
    }

    //读操作时捕获到异常时调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
